package com.example.service;

import cn.hutool.core.util.StrUtil;
import com.example.entity.Account;
import com.example.entity.User;
import com.example.exception.CustomerException;
import com.example.mapper.UserMapper;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public List<User> selectAll() {
        return userMapper.selectAll(null);
    }


    public PageInfo<User> selectPage(Integer pageNum, Integer pageSize, String name) {
        // 开启分页查询
        PageHelper.startPage(pageNum,pageSize);
        List<User> list = userMapper.selectAll(name);
        return PageInfo.of(list);
    }
    public void add(User user){
        // 判断账号是否重复
        if(userMapper.selectByUsername(user.getUsername())!=0){
            throw new CustomerException("账号重复");
        }
        // 密码为空时，默认密码为123456
        if(StrUtil.isBlank(user.getPassword())){
            user.setPassword("123");
        }
        if(StrUtil.isBlank(user.getName())){
            user.setUsername(user.getUsername());
        }
        System.out.println("user======>"+user);
        if(StrUtil.isBlank(user.getAvatar())){
            user.setAvatar("http://svgzmkt0s.hn-bkt.clouddn.com/avatar/user/tx2.jpg");
        }
        userMapper.insert(user);
    }

    public void update(User user) {
//        if(userMapper.selectByUsername(user.getUsername())!=0){
//            throw new CustomerException("账号重复");
//        }
        userMapper.updateById(user);
    }

    public void deleteById(Integer id) {
        userMapper.deleteById(id);
    }

    public void deleteBatch(List<User> list) {
        for (User user : list) {
            this.deleteById(user.getId());
        }
    }

    public User login(String username, String password) {
        User user = userMapper.selectByUsernameAndPassword(username, password);
        String token= TokenUtils.createToken(user.getId() + "-" + "USER",user.getPassword());
        user.setToken(token);
        return user;
    }

    public void register(User user) {
        this.add(user);
    }

    public Account selectById(String userId) {
        return userMapper.selectById(userId);
    }

    public void updatePassword(Account account) {
//        userMapper.updateById(account);
        Account user = TokenUtils.getCurrentUser();
        System.out.println("user=====>"+user);
        if(!user.getPassword().equals(account.getPassword())){
            throw new CustomerException("原密码错误");
        }
        // 修改密码
        Account user1 = userMapper.selectById(account.getId().toString());
        user1.setPassword(account.getNewPassword());
        userMapper.updateById(user1);
    }

}